#include"mutex.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<iostream>
#include<unistd.h>
using namespace std;
class thread_set{
    public:
    thread_set(mutex *plock,string name):_name(name),_plock(plock){}
    string getname(){ return _name;}
    mutex *getlock(){ return _plock;}
    ~ thread_set(){}
 private:
 std:: string _name;
 mutex *_plock;
};
// 创建2个进程模拟抢票：
int ticket = 1000;
void *route(void *arg)
{
    thread_set * ts = static_cast<thread_set*>(arg);
    while (1)
    {   //保护临界区
        {
          mutexguard md(*(ts->getlock()));
        if (ticket > 0) // 1. 判断
        {
            usleep(1000);                               // 模拟抢票花的时间
            printf("%s sells ticket:%d\n", ts->getname().c_str(), ticket); // 2. 抢到了票
            ticket--;                                   // 3. 票数--
          
        }
        else
        {
          
            //这里还需要解锁否则到最后抢完票线程加锁后有其他线程不能被join进而阻塞住

            break;
        }
    }
    }
    return nullptr;
}


int main()
{
    pthread_t t1,t2;
    mutex mx;
    thread_set s1(&mx,"thread-1");
    thread_set s2(&mx,"thread-2");
    pthread_create(&t1, NULL, route, &s1);
    pthread_create(&t2, NULL, route, &s2);
   

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    
}